'use strict';

const path = require('path');
const semver = require('semver');
const colors = require('colors');
const userHome = require('user-home');
const pathExists = require('path-exists').sync;
const commander = require('commander');

const log = require('@caiheping-cli-dev/log');
const exec = require('@caiheping-cli-dev/exec');
const pkg = require('../package.json');
const constant = require('./const');

const program = new commander.Command();

async function core() {
    try {
        await prepare()
        registerCommand();
    } catch (e) {
        log.error(e.message);
        if (process.env.LOG_LEVEL === 'verbose') {
            console.log(e);
        }
    }
}

async function prepare() {
    checkRoot();
    checkUserHome();
    setCliPathToEnv();
    await checkGlobalUpdate();
}

// 脚手架命令注册
function registerCommand() {
    program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command> [option]')
    .version(pkg.version)
    .option('-v --version')
    .option('-tp --targetPath <targetPath>', '是否指定本地调试文件路径')
    .option('-d --debug', '是否开启调试模式', false);

    // init命令
    program
    .command('init <packageName>')
    .option('-f --force', '是否强制初始化')
    // .option('-tp --targetPath <targetPath>', '是否指定本地调试文件路径')
    .action(exec);

    // 监听targetPath， 并放到系统环境变量上
    program.on('option:targetPath', (targetPath) => {
        // console.log(targetPath, 999);
        process.env.CLI_TARGET_PATH = targetPath;
    });

    // 开启debug模式
    program.on('option:debug', () => {
        process.env.LOG_LEVEL = 'verbose';
        log.level = process.env.LOG_LEVEL;
        log.verbose('debug', '正在调试中...');
    });

    // 对未知的命令监听
    program.on('command:*', (operands) => {
        console.log(operands);
        console.error(`error: 未知的命令 '${operands[0]}'`);
        const availableCommands = program.commands.map(cmd => cmd.name());
        console.log(colors.green(`可用命令：${availableCommands}`));
    });

    program.parse(process.argv); // 完成脚手架注册
}

// 检查root账户
function checkRoot() {
    const rootCheck = require('root-check');
    rootCheck();
}

// 检查用户主目录是否存在
function checkUserHome() {
    if (!userHome || !pathExists(userHome)) {
        throw new Error(colors.red('当前登录用户主目录不存在'));
    }
}

// 配置cli路径到全局变量
function setCliPathToEnv() {
    if (!process.env.CLI_HOME) {
        process.env.CLI_HOME_PATH = path.join(userHome, constant.DEFAULT_CLI_HOME);
    }
}

async function checkGlobalUpdate() {
    // 获取当前版本号和模块名
    const currentVersion = pkg.version;
    const npmName = pkg.name;
    // 调用npm API，获取所有版本号
    const { getNpmSemverVersion } = require('@caiheping-cli-dev/get-npm-info');
    const lastVersions = await getNpmSemverVersion(npmName, currentVersion);
    if (lastVersions && semver.gt(lastVersions, currentVersion)) {
        log.warn(colors.yellow(`请手动更新 ${npmName}, 当前版本是：${currentVersion}, 最新版本是：${lastVersions}
            更新命令： npm install -g ${npmName}
        `));
    } else {
        log.info('当前已是最新版本了');
    }
}

module.exports = core;
